package com.jk.controller;

import com.jk.bean.*;
import com.jk.client.LoginClient;
import com.jk.service.ShorService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import util.CheckImgUtil;
import util.Constant;
import util.QueryParam;
import util.Result;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("view")
public class LoginController {
    @Resource
    private ShorService shorService;

    @Resource
    private LoginClient loginClient;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //===jiaose
    @RequestMapping("getRole")
    public String getRole(String userId, Model mo) {
        mo.addAttribute("msg",userId);
        return "role";
    }





    @RequestMapping("toView")
    public String viewName(String viewName) {

        return viewName;
    }


    @ResponseBody
    @RequestMapping("loginStaff")
    public boolean loginStaff(Staff staff, HttpSession session){

     Staff data =  loginClient.loginStaff(staff);

         if(data!=null){
             session.setAttribute("msg","欢迎   "+data.getStaffName()+"  ");
             session.setAttribute("staff",data);
             return true;
         }
          return false;
        }


        //注销
    @RequestMapping("removeSession")
    public String removeSession(HttpSession session){
        session.invalidate();
        return "login";
    }

    //=====权限登录
    @RequestMapping("login")
    public String login() {

        return "toLogin";
    }

    @RequestMapping("reject")
    public String reject() {
        return "reject";
    }

    @ResponseBody
    @RequestMapping("toLogin")
    public String toLogin(String code, Staff sd, HttpSession session, HttpServletResponse response) {
        //先验证随机码
        String randomCode = (String) session.getAttribute("checkcode");
        if (randomCode.equalsIgnoreCase(code)) {


            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(sd.getStaffName(), sd.getStaffPwd());

            try {
                subject.login(usernamePasswordToken);
            } catch (UnknownAccountException e) {
                System.out.println("用户名不存在");
                session.setAttribute("msg", "用户名不存在");
                return "4";
            } catch (IncorrectCredentialsException e) {
                System.out.println("密码或和用户名不一致");
                session.setAttribute("msg", "密码或和用户名不一致");
                return "3";

            } catch (AuthenticationException e) {
                e.printStackTrace();
                session.setAttribute("msg", "未知的错误");
                return "1";
            }
            Staff user = shorService.getUser(sd.getStaffName());
            session.setAttribute("user", user.getStaffName());
            //判断有没有勾选住密码
            Cookie cookieLoginacct = new Cookie("user_Loginacct", user.getStaffName());
            Cookie cookiepwd = new Cookie("user_pwd", user.getStaffPwd());
            System.out.println("记住密码====>" + user.getRememberPswd());
            if (sd.getRememberPswd() == 1) {
                //勾选  记住
                System.out.println("====>1111111111");
                //设置过期时间  保存七天
                cookieLoginacct.setMaxAge(604800);
                cookiepwd.setMaxAge(604800);
                //当前应用任何目录下都能访问cookie
                cookieLoginacct.setPath("/");
                cookiepwd.setPath("/");

                System.out.println(cookieLoginacct);
                System.out.println(cookiepwd);
                //此时cookie还在服务器上  要把cookie发送到浏览器上  通过相应对象
                response.addCookie(cookieLoginacct);
                response.addCookie(cookiepwd);
            } else if (sd.getRememberPswd() == 2) {
                System.out.println("====>阿萨大苏打飒飒打撒");
                cookieLoginacct.setMaxAge(0);
                cookiepwd.setMaxAge(0);
                cookieLoginacct.setPath("/");
                cookiepwd.setPath("/");
                response.addCookie(cookieLoginacct);
                response.addCookie(cookiepwd);
            }
            return "2";
        }

        return "5";
    }

    //====获取登录页面的验证码？图片验证码
    @RequestMapping("getCode")
    @ResponseBody
    public void getCode(HttpServletRequest request, HttpServletResponse response) {

        CheckImgUtil.buildCheckImg(request, response);
    }

    //====手机号短信验证


    @ResponseBody
    @RequestMapping("getCodeByPhone")
    public Result getCodeByPhone(QueryParam queryParam){

        //日历
        GregorianCalendar phoneToRidesTime = new GregorianCalendar();

        Result result = new Result();
        //查询手机号有没有注册
        Staff user=shorService.existsPhone(queryParam.getUserPhone());
        //查询黑名单有没有此用户
        Staff HeUser=shorService.heiPhone(queryParam.getUserPhone());
        if(HeUser!=null){
            result.setHeMingDan_phone(1);//黑名单
            return result;
        }
        if(user==null){
            result.setExists_phone(0);//代表没有注册过
            return result;
        }

        //每次都从redis中取一下当前手机号 如果有值 说明是刷新界面多次获取验证码
        boolean hasPhone = redisTemplate.hasKey(Constant.multiple_code+queryParam.getUserPhone());
        boolean count= redisTemplate.hasKey(queryParam.getUserPhone());   //*** 手机号的key是否存在rides中 用来做 一小时之内只能存三次
        if(hasPhone){
            //两次获取验证码的时间没有超过40s
            result.setCode(2);//code =2 已经获取过验证码
        }else{
            if(!count){   //如果如果不存在此手机号表名第一次获取验证码
                Date date = new Date();
                phoneToRidesTime.setTime(date);
                phoneToRidesTime.add(phoneToRidesTime.MINUTE,10);   //往后延迟60分钟
                //设置60分钟过期 并且次数为0
                redisTemplate.opsForValue().set(queryParam.getUserPhone(), "0");
            }
            Date date1 = new Date();

            boolean  bo=phoneToRidesTime.getTime().before(date1);  //before之前的意思
            System.out.println(date1+"当前时间-----1");
            System.out.println(phoneToRidesTime+"之前添加的时间-----2");

            if(bo){
                redisTemplate.delete(queryParam.getUserPhone());
                Date date2 = new Date();
                phoneToRidesTime.setTime(date2);
                phoneToRidesTime.add(phoneToRidesTime.MINUTE,10);
                redisTemplate.opsForValue().set(queryParam.getUserPhone(), "0");
            }

            //str是当日申请的次数
            String str= redisTemplate.opsForValue().get(queryParam.getUserPhone()).toString();
            if(!str.equals("3")) {
                // 产生一个6位验证码
                int code = (int) (Math.random() * 899999) + 100000;
                System.out.println(code);

                //Integer integer = redisTemplate.opsForValue().get(Constant.verification_code+queryParam.getPhone_number());
                //System.out.println("====这个是你想要的====>"+integer);
                // 并设置60秒的过期时间  判断是否多次登录
                redisTemplate.opsForValue().set(Constant.multiple_code + queryParam.getUserPhone(), code + "", 20, TimeUnit.SECONDS);

                result.setCode(1);//code =1 代表验证码发送成功
                int ss=Integer.valueOf(str)+1;
                redisTemplate.opsForValue().set(queryParam.getUserPhone(), ss+"");
            }else{

                result.setCode(4);//code =4 代表验证码五分钟之内三次
            }
        }
        return result;
    }

    //=======短信验证
    @ResponseBody
    @RequestMapping("checkCode")
    public String checkCode(QueryParam pm,HttpSession session){

        String verify_code = pm.getGetCode();
        // 比对验证码
        String codeFromRedis = redisTemplate.opsForValue().get(Constant.multiple_code +""+pm.getUserPhone());
        System.out.println(verify_code+"<======比对=====>"+codeFromRedis);
        if (codeFromRedis != null && codeFromRedis.equals(verify_code)) {
            // 用户输入的验证码是对的

            // 登录成功 根据手机号 查询出用户的信息 保存到session
            Staff user = shorService.existsPhone(pm.getUserPhone());

            //必须以user为key 不然拦截器会认为没有登录
            session.setAttribute("user", user);

            //登录成功后验证码就失效
            redisTemplate.delete(Constant.multiple_code + pm.getUserPhone());

            return "1";//校验成功
        }
        return "0";//验证码有误校验失败
    }
    //=====注册
    @ResponseBody
    @RequestMapping("goRegister")
    public String goRegister(Staff sd){

        Staff sf = shorService.queryStaff(sd);

        if(sf!=null){
            return "2";
        }

        shorService.goRegister(sd);

        return "1";
    }
    //====角色
    @ResponseBody
    @RequestMapping("getHaa")
    public SendPage queryRole(Page page){
        SendPage pag=shorService.queryRole(page);
        return pag;
    }
    //==单个角色
    @ResponseBody
    @RequestMapping("updaRole")
    public Role updaRole(String id){

        return shorService.updaRole(id);
    }
    //=====删除角色
    @ResponseBody
    @RequestMapping("delRole")
    public String delRole(String id){
        shorService.delRole(id);
        return null;
    }
    //===增加角色
    @RequiresPermissions(value = "pf:add")
    @ResponseBody
    @RequestMapping("addRole")
    public String addRole(Role role){
        shorService.addRole(role);
        return null;
    }
    //===权限查询
    @ResponseBody
    @RequestMapping("queryPer")
    public SendPage queryPer(Page page){
        SendPage pag =shorService.queryPer(page);
        return pag;
    }
    //=====权限删除
    @RequiresPermissions(value = "pf:add")
    @ResponseBody
    @RequestMapping("delPer")
    public String delPer(String id){
        shorService.delPer(id);
        return null;
    }
    //====修改权限
    @ResponseBody
    @RequestMapping("updaPer")
    public Permission updaPer(String id){
        return  shorService.updaPer(id);
    }

    //====增加权限
    @RequiresPermissions(value = "pf:add")
    @ResponseBody
    @RequestMapping("addPer")
    public String addPer(Permission per){
        shorService.addPer(per);
        return null;
    }
    //====删除
    @RequiresPermissions(value = "pf:add")
    @ResponseBody
    @RequestMapping("delStaff")
    public String delStaff(String id){
        shorService.delStaff(id);
        return null;
    }

}
